// Author: wsfuyibing <682805@qq.com>
// Date: 2025-06-18

package start

import (
	"context"
	"fmt"
	"gitee.com/go-libs/db-xorm/db"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/logics/master/ticket/record"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/kind"
	"server/app/lib"
	"strings"
)

// Logic
// 设置作钓开始.
type Logic struct {
	record.Logic

	admin  *models.ArcadeAdmins
	arcade *models.Arcades

	affects       int64
	ignored       bool
	kind          kind.ArcadeAdminOperation
	kindContent   string
	ticket        *models.Ticket
	ticketRecord  *models.TicketRecord
	ticketSession *models.TicketSession
	user          *models.Users

	request  *Request
	response *Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: &Response{},
	}
}

// After
// 后置日志.
func (o *Logic) After(ctx context.Context, _ iris.Context, _ result.Result) {
	if o.affects > 0 {
		_, _ = services.NewArcadeLogsService().Add(ctx,
			o.arcade, o.admin, o.kind, o.kindContent, map[string]any{
				"Id": o.ticketRecord.Id,
			},
		)
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Json(i, o.request); err == nil {
		o.arcade, o.admin = lib.Arcade.GetMaster().GetArcade(i)
	}
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err error
		res = result.New()
	)

	// 1. 事务处理.
	if err = db.Transaction(ctx,
		o.RunCheck,
		o.RunUpdate,
	); err != nil {
		return res.WithError(err)
	}

	// 2. 绑定数据.
	return res.With(o.response.With(o.ticketRecord))
}

// RunCheck
// 查询数据.
func (o *Logic) RunCheck(ctx context.Context, sess *db.Session) (err error) {
	var has bool

	// 1. 购买记录.
	if o.ticketRecord, has, err = services.NewTicketRecordService(sess).Dao.GetById(ctx, o.request.Id); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}

	// 2. 无效记录.
	if !has || o.ticketRecord.ArcadeId != o.arcade.Id {
		err = errs.ErrTicketRecordNotFound
		return
	}

	// 3. 状态错误.
	if !o.ticketRecord.State.IsWaiting() {
		o.ignored = true
	}

	// 4. 渔票数据.
	if o.ticket, has, err = services.NewTicketService(sess).Dao.GetById(ctx, o.ticketRecord.TicketId); err != nil {
		err = errs.ErrDatabaseQuery
		return
	} else if !has || o.ticket.ArcadeId != o.arcade.Id || o.ticket.Deleted.IsYes() {
		err = errs.ErrTicketNotFound
		return
	}

	// 5. 场次数据.
	if o.ticketSession, has, err = services.NewTicketSessionService(sess).Dao.GetById(ctx, o.ticketRecord.SessionId); err != nil {
		err = errs.ErrDatabaseQuery
		return
	} else if !has || o.ticketSession.ArcadeId != o.arcade.Id || o.ticketSession.Deleted.IsYes() {
		err = errs.ErrTicketSessionNotFound
		return
	}

	// 6. 钓友数据.
	if o.user, has, err = services.NewUsersService(sess).Dao.GetById(ctx, o.ticketRecord.UserId); err != nil {
		err = errs.ErrDatabaseQuery
		return
	} else if !has {
		err = errs.ErrUserNotFound
		return
	}

	// 7. 校验通过.
	return
}

// RunUpdate
// 更新状态.
func (o *Logic) RunUpdate(ctx context.Context, sess *db.Session) (err error) {
	// 1. 忽略任务.
	//    重复操作或状态错误时触发.
	if o.ignored {
		return
	}

	// 2. 更新状态.
	if o.affects, err = services.NewTicketRecordService(sess).Dao.UpdateFieldsById(ctx, map[string]any{
		"state":      kind.TicketRecordStarted,
		"time_start": o.request.TimeStart,
		"time_end":   o.request.TimeEnd,
	}, o.ticketRecord.Id); err != nil {
		err = errs.ErrDatabaseQuery
	} else if o.affects > 0 {
		o.RunUpdateToLog()
	}
	return
}

// RunUpdateToLog
// 处理日志.
func (o *Logic) RunUpdateToLog() {
	list := []string{
		fmt.Sprintf(`%s 票 %v 场的 %s 钓友开始作钓`, o.ticket.Name, o.ticketSession.Date, o.user.Nickname),
		fmt.Sprintf(`作钓时从 %s 到 %s`, o.request.TimeStart, o.request.TimeEnd),
	}

	o.kind = kind.ArcadeAdminOperationTicketRecordStart
	o.kindContent = strings.Join(list, ",")
}
